<template>
	<div class="spread con customer_index">
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  	<el-breadcrumb-item :to="{ path: '/customer' }">homepage</el-breadcrumb-item>
		  	<el-breadcrumb-item>Add BOM</el-breadcrumb-item>
		</el-breadcrumb>
	<div>
		
		<div style="margin-top:10px;">
			<!--<el-button  type="danger" icon="el-icon-tickets" @click="AddRFQ()">Add RFQ</el-button>
			<el-button  type="danger" icon="el-icon-tickets" @click="AddNew()">Add New</el-button>
			<el-button  type="danger" icon="el-icon-tickets" @click="view()">View</el-button>
			<el-button  type="danger" icon="el-icon-tickets" @click="AddNewVender()">Add Vender</el-button>
			<el-button  type="danger" icon="el-icon-tickets" @click="Delete()">Delete</el-button>  -->
			
			 <el-form  :inline="true" :model="form" :rules="formRules" ref="form" >
					<el-form-item label="Customer" prop="CustomerID"  >
					  <el-select v-model="form.CustomerID" placeholder="Please choose" filterable clearable  @change="changeCustomer($event)" >
						  <el-option v-for="(item, index) in CustomerList" :key="index" :label="item.CompanyName" :value="item.CustomerID"></el-option>
					  </el-select>
					  <el-button type="info" icon="el-icon-search" @click="searchCustomer"></el-button>
					</el-form-item>
					
					<el-form-item label="Contact" prop="CompanyContactID"  >
						<el-select v-model="form.CompanyContactID" placeholder="Please choose"   filterable clearable>
							  <el-option v-for="(item, index) in ContactList" :key="index" :label="item.ContactName" :value="item.CompanyContactID"></el-option>
					    </el-select>
					</el-form-item>
					
					
					<el-form-item label="SalesRep" prop="SalesRepID"  >
					  <el-select v-model="form.SalesRepID" placeholder="Please choose"  filterable clearable >
					  		<el-option v-for="(item, index) in SalesRepList" :key="index" :label="item.employeeName" :value="item.employeeID"></el-option>
					  </el-select>
					</el-form-item>
					<el-form-item label="RequestDate" >
							<el-date-picker
						      v-model="form.RequestDate"
						      type="date"
						      format="yyyy-MM-dd"
						      placeholder="Select date">
						    </el-date-picker>
					</el-form-item>
					<el-form-item >
					 <el-button type="primary"  @click="submitForm('form')">Start Import</el-button>
					</el-form-item>
					
					<div style="margin-top:-20px;">
						<el-form-item >
						<span style="margin-left:20px; ">Brand / PartNo / Customer PartNo / Quantity / TargetPrice / DateCode / Package / Remark</span>
						    <el-input type="textarea"  :autosize="{ minRows: 5, maxRows: 10001}" v-model="form.Remarks" style="width:100%;"></el-input>
						</el-form-item>
					</div>
			 </el-form>
		</div>
	</div>
	
		<div>
			<el-divider content-position="left">Preview</el-divider>
			<el-button type="primary"  @click="getBOMList">Save</el-button>
			<el-button type="primary"  @click="getBOMListClosed">Closed</el-button>
		</div>
			
		
		<el-table 
			v-loading="loading"
			element-loading-text="拼命加载中"
		    :data="tableData"
		    style="width: 100%"
			:height="tableHeight"
		    border
		    fit
		    highlight-current-row
    		@current-change="shandleCurrentChange"
    		@sort-change='tableSortChange'
		   >
		  <!-- <el-table-column label="V" width="40">
				<template slot-scope="scope">
					<span ></span>
				</template>
			</el-table-column>
			<el-table-column label="H" width="40">
				<template slot-scope="scope">
					<span></span>
				</template>
			</el-table-column> -->
			
			<el-table-column label="QN" width="50" >
				<template slot-scope="scope">
					<span>{{ scope.row.QuoteNum }}</span>
				</template>
			</el-table-column>
			<el-table-column label="SalesRep" width="100" >
				<template slot-scope="scope">
					<span>{{ scope.row.SalesRepIDName }}</span>
				</template>
			</el-table-column>
			<el-table-column label="CustomerName" width="150" >
				<template slot-scope="scope">
					<span>{{ scope.row.CustomerName }}</span>
				</template>
			</el-table-column>
			<el-table-column label="Brand" width="130">
				<template slot-scope="scope">
					<span>{{ scope.row.BrandName }}</span>
				</template>
			</el-table-column>
			<el-table-column label="PartNo" width="160">
				<template slot-scope="scope">
					<span>{{ scope.row.PartNo }}</span>
				</template>
			</el-table-column>
			<el-table-column label="Customer PartNo" width="180">
				<template slot-scope="scope">
					<span>{{ scope.row.CustomerPartNo }}</span>
				</template>
			</el-table-column>
			<el-table-column label="Qty" width="65"> 
				<template slot-scope="scope">
					<span>{{ scope.row.Quantity }}</span>
				</template>
			</el-table-column>
			<el-table-column label="TargetPrice" width="105">
				<template slot-scope="scope">
					<span>{{ (scope.row.TargetPrice) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="DateCode" width="95">
				<template slot-scope="scope">
					<span>{{ scope.row.DateCode }}</span>
				</template>
			</el-table-column>
			<el-table-column label="Package" width="90">
				<template slot-scope="scope">
					<span>{{ scope.row.Package }}</span>
				</template>
			</el-table-column>
			<el-table-column label="Remark" width="80">
				<template slot-scope="scope">
					<span>{{ scope.row.Remark }}</span>
				</template>
			</el-table-column>
			<el-table-column label="LeadFree" width="90">
				<template slot-scope="scope">
					<span>{{ scope.row.LeadFree }}</span>
				</template>
			</el-table-column>
			<el-table-column label="Status" width="90">
				<template slot-scope="scope">
					<span>{{ scope.row.StatusName }}</span>
				</template>
			</el-table-column>
		  </el-table>
		  <!-- Customer 搜索 -->	
					<el-dialog  title ="Search Customer" :visible.sync="dialogTableCustomer" customClass="customWidth_50">
						  <el-input v-model="CustomerName" placeholder="Search Customer Name" style="width:32%;" clearable></el-input>
						  <el-button type="primary" icon="el-icon-search" @click="CustomerNameSearch">Search</el-button>
						  <el-table :data="tableCustomerList" style="margin-top:1px;"> 
								<el-table-column property="CustomerStatusName" label="Status" width="80" ></el-table-column>
							    <el-table-column label="CompanyName"  align="center" width="220">
								   <template slot-scope="scope" > 
										<span @click="openHomeCustomer(scope.row)" style="cursor:pointer">{{ scope.row.CompanyName }}</span>
								   </template>
							    </el-table-column>
							    <el-table-column property="CompanyAlias" label="Alias" width="200" ></el-table-column>
								<el-table-column property="State" label="Region" width="80" ></el-table-column>
								<el-table-column property="CountryName" label="Country" width="100" ></el-table-column>
								<el-table-column property="CompanyAddress" label="CompanyAddress" width="150" ></el-table-column>
						  </el-table>
					</el-dialog>
		  
		  
	</div>
</template>

<script type="text/javascript">
	export default {
		data(){
			var sdDate = [];
			return {
				loading:false,
				tableData: [],
				tableHeight: 220,
				token:"",
				listQuery:{sortby:'',order:'desc'},
				fileDwonload:false,
				
				
				form:{
					SalesRepID:'',
					CompanyContactID:'',
					RequestDate:'',
					Remarks:'',
					
					},
				formRules:{
						 CustomerID: [
						            { required: true, message: 'Please choose Custome', trigger: 'change' }
						          ],
						 CompanyContactID: [
				            { required: true, message: 'Please choose Contact', trigger: 'change' }
				          ], 
				   		 SalesRepID:[
				     		{ required: true, message: 'Please choose SalesRep', trigger: 'change' }
				     		],   
						
						
					},
				CustomerList:[],  
				SalesRepList:[],
				ContactList:[],
				CustomerID:'',
				dialogTableCustomer:false,
				CustomerName:'',
				tableCustomerList:[],
				
				
				
				currentRow: [],
				page: {
					 total: 0,
					 size: 1, 
					 currentPage: 1,
					 num: 1,
					
					 },
					
					}
				},
				
				
				
		created(){
			this.form.RequestDate =this.getNowFormatDate();
			this.getSalesRepList();
			this.getContactList();
			console.log(this.$route.query);
			this.CustomerID = this.$route.query.CustomerID;
			this.form.CustomerID=parseInt(this.CustomerID);
			
			this.getCustomerList();
		},
		mounted() {
			const that = this;
			// 动态设置表格高度适应窗口
			window.onresize = () => {
				let a = window.innerHeight;
				that.tableHeight = a-403;
			}
		},
		methods:{
			getCustomerList(){
				axios.get('/api/CustomerCompany?CustomerID='+this.CustomerID).then(result => {
					this.CustomerList = result.data.result.data;
					});
			
				//this.loading = true;
			},
			//changeCustomer
			changeCustomer(e){ 
				this.form.CompanyContactID ='';
				 axios.get('/api/companyContactChange?CustomerID=' +e).then(result => {
							this.ContactList = result.data.result;
						});
				
			},
			//搜索searchCustomer
			searchCustomer(){
				this.dialogTableCustomer=true;
				this.CustomerList=[];
		    	this.CustomerName='';
				this.tableCustomerList=[];
			},
			//CustomerNameSearch
			CustomerNameSearch(){
				if(this.CustomerName == '' || this.CustomerName.length<=1){
	    				this.$alert('Text cannot be empty,more than 2 strings, please enter', 'Tips', {
			                  confirmButtonText: 'confirm'
					        });
					        return;
	    			}
	    			axios.get('/api/customer/customerlist?companyname='+this.CustomerName).then(result => {
						this.tableCustomerList = result.data.result;
					});
					
					
			},
			openHomeCustomer(row){
	    			this.dialogTableCustomer =false;
			        this.form.CustomerID = parseInt(row.CustomerID);
			        this.form.Customerparam = row;
			        this.CustomerID = parseInt(row.CustomerID);
			        this.getCustomerList();
			        var CID = this.form.CustomerID;
			        this.form.CompanyContactID ='';
			        this.Contact(CID);
			},
			Contact(e){
				axios.get('/api/companyContactChange?CustomerID=' +e).then(result => {
								this.ContactList = result.data.result;
						});
				},
			//导入数据 submitForm
			submitForm(formName){
				this.$refs[formName].validate((valid) => {
		          if (valid) {
		          	axios.post('/api/AddBOM',this.form)
					.then(result => {
						if(result.data.code == 200) {
							this.$notify.success({
								title: 'Success',
								message: result.data.message
							});
							this.tableData = result.data.result;
							
						
						}else{
							this.$notify.error({
								title: 'Fail',
								message: result.data.message
							});
						}
							
						})
					.catch(error => {
						
					})
		          }
		        });
				
				
				
				
			},
			
			getCustomerTable(){
				axios.get('/api/AddBOM?page='+this.page.num).then(result => {
					if (result.data.code == 200) {
						this.tableData = result.data.result;
						//this.page.total = result.data.total;
						//this.page.size = result.data.size;
						//this.page.per_page = result.data.last_page;
						//this.loading = false;
					} else {
						this.$notify.error({
							title: 'Fail',
							message: result.data.message
						});
					}
				})
				.catch(error => {
					this.$notify.error({
						title: 'Fail',
						message: 'Error'
					});
				});
			},
			
			getContactList(){
			      var CompanyID =this.$route.query.CompanyID; 
			      	axios.get('/api/companycontact?CompanyID='+CompanyID).then(result => {
							this.ContactList = result.data.result;
						});
			      },
		    getSalesRepList(){
		      		axios.get('/api/getsalesRep').then(result => {
						this.SalesRepList = result.data.result;
					});
		      },
			//时间
			shandleCurrentChange(data) {
			        this.currentRow = data;
			      },
			      tableSortChange(column){
				if (column.order === 'descending') {
			        this.listQuery.sortby = column.prop
			        this.listQuery.order = 'desc'
			      } else {
			        this.listQuery.sortby = column.prop
			        this.listQuery.order = 'asc'
			      }
			},
						
		    handerSearch(){
		  		this.page.num = 1;
		   	 	
		    },
		    getCookie(name){
				var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
				if(arr=document.cookie.match(reg)){
					return unescape(arr[2]);
				}else{
					return null;
				}
			},
		    handleCurrentChange(val) { 
               this.page.num = val;
                this.getCostomerList();
            },
		    isTimeString(time){
		    	if(time=='' || time== null || time == 'undefined'){
		    	 return '';
		    	}else{
		    		return time.substring(0,10);
		    	}
		    },
		    getStatusValue(val){
		    	if(val == 1){
		    		return 'NewCustomer';
		    	}else if(val == 100){
		    		return 'Active';
		    	}else{
		    		return 'Open';
		    	}
		    	
		    },
		   getNowFormatDate(){
			    var date = new Date();
			    var seperator1 = "-";
			    var year = date.getFullYear();
			    var month = date.getMonth() + 1;
			    var strDate = date.getDate();
			    if (month >= 1 && month <= 9) {
			        month = "0" + month;
			    }
			    if (strDate >= 0 && strDate <= 9) {
			        strDate = "0" + strDate;
			    }
			    var currentdate = year + seperator1 + month + seperator1 + strDate;
			    return currentdate;
			},
			
			//getBOMList
		getBOMList(){
			if(this.tableData.length<=0){
				this.$alert('Please Import Data.', 'Tips', {
                  confirmButtonText: 'confirm'
		        });
		        return;
			
			}
			console.log(2222,this.tableData);
			axios.post('/api/getAddBomList',this.tableData)
					.then(result => {
						if (result.data.code == 200) {
							this.$notify.success({
								title: 'Success',
								message: result.data.message
							});
							
						
						} else {
							this.$notify.error({
								title: 'Fail',
								message: result.data.message
							});
						}
					})
					.catch(error => {
						
					})
			
			},
		getBOMListClosed(){
			  this.$router.push({ path: '/customer'});
		},
			
		  toDecimal(x) {
			      var f = parseFloat(x); 
			      if (isNaN(f)) { 
			        return false; 
			      } 
			      var f = Math.round(x*100)/100; 
			      var s = f.toString(); 
			      var rs = s.indexOf('.'); 
			      if (rs < 0) { 
			        rs = s.length; 
			        s += '.'; 
			      } 
			      while (s.length <= rs + 2) { 
			        s += '0'; 
			      } 
			      return s; 
		    },
		    addTime(m){
		    	return m<10?'0'+m:m 
		    },
		    
			getTime(){
				var date = new Date()
			    let y = date.getFullYear()
			    let m = date.getMonth() + 1
			    let d = date.getDate()
			    let time = y + '-' + m + '-' + d;
				let d1 = '01';
				let time1 = y + '-' + m + '-' + d1;
				this.rantime[0]=time1;
			    this.rantime[1]=time;
			},
			
			timeFormat(shijianchuo)
			{
				//shijianchuo是整数，否则要parseInt转换
				var time1 = new Date(shijianchuo);
				var y = time1.getFullYear();
				var m = time1.getMonth()+1;
				var d = time1.getDate();
				var h = time1.getHours();
				var mm = time1.getMinutes();
				var s = time1.getSeconds();
				return y+'-'+this.addTime(m)+'-'+this.addTime(d)+' '+this.addTime(h)+':'+this.addTime(mm)+':'+this.addTime(s);
			}
			
		}
	}
</script>

<style lang="scss">
	.customer_index{
		.sort.el-select .el-input {
			width: 140px;
		}
	}
  	.el-table .warning-row {
    	background: oldlace;
  	}
  	.el-select .el-input {
    	width: 120px;
  	}
  	.input-with-select .el-input-group__prepend {
    	background-color: #fff;
  	}
  	.el-table .success-row {
    	background: #f0f9eb;
  	}
  	.con{
	    .el-breadcrumb{ 
	      	height: 40px;
	    }
	 .juli{
	 	margin-left:10px;
	 	}   
  	}
	.el-pagination__total{
		float: left;
		margin-top: 2px;
	}
	.pages{
		float: right;
	}
</style>
